<script setup>
import webConfig from '@/GlobalParas';
import axios from 'axios';
import { ref, watch } from 'vue';
const treeData=ref([]);
const buildTree = (data, parentId = null) => {
    return data
        .filter(item => item.parentFunctionId === parentId)
        .map(item => ({
            title: item.functionName,
            key: item.tableKey,
            children: buildTree(data, item.tableKey)
        }));
}

const checkedKeysback = ref([]);// 不完全选中子节点时 会传入对应父节点 方便传入后端
const onCheck = (checkedKeys, { halfCheckedKeys }) => {
    const allCheckedKeys = [...checkedKeys, ...halfCheckedKeys];
    checkedKeysback.value = allCheckedKeys;
    // console.log(checkedKeysback.value);
}; //不全选子节点时传入父节点

const getAllRoleFunction = ()=>{ //获取所有功能并调用函数构建树
let url = webConfig.postUrl + '/systemFunction/getAllFunctions'
axios.post(url).then(res => {
    treeData.value = buildTree(res.data)
    // console.log(treeData)
})
}
getAllRoleFunction();

const role = ref({
    tableKey: crypto.randomUUID(),
    deptId:'',
    roleName: '',
    sort: '',
    flagDel: 0
})
const emit=defineEmits(["addInfo"]);
const onFinish = values => {
    emit("addInfo", role.value, checkedKeysback.value)
    role.value = {
        tableKey: crypto.randomUUID(),
        deptId: '',
        roleName: '',
        sort: '',
        flagDel: 0
    }
    checkedKeys.value = [];
    selectedKeys.value = [];
};
const onFinishFailed = errorInfo => {
  console.log('Failed:', errorInfo);
};
const expandedKeys = ref(['001','002','003']);//默认展开的节点
const selectedKeys = ref([]);
const checkedKeys = ref([]);
</script>

<template>
    <a-form :model="role" :label-col="{ span: 4 }" @finish="onFinish" @finishFailed="onFinishFailed">
        <a-form-item :wrapper-col="{ span: 14 }" label="角色名" name="roleName"
            :rules="[{ required: true, message: '请输入角色名' },{ min: 0, max: 50,message: '字数不得超过50'}]">
            <a-input v-model:value="role.roleName" />
        </a-form-item>
        <a-form-item label="权限分配" style="margin-left: 10px;">
            <div style="display: flex; justify-content: space-between;">
                <div>
                    <a-tree @check="onCheck" v-model:expandedKeys="expandedKeys" v-model:selectedKeys="selectedKeys"
                        v-model:checkedKeys="checkedKeys" checkable :tree-data="treeData">
                        <template #title="{ title }">
                            {{ title }}
                        </template>
                    </a-tree>
                </div>
                <a-button type="primary" html-type="submit" style="margin-right: 60px; align-self:flex-end;" >确认</a-button>
            </div>
        </a-form-item>

    </a-form>
</template>

<style scoped>

</style>